package repository

import (
	model "antiquity_map/internal/models"
	"fmt"

	"gorm.io/gorm"
)

type UserRepository interface {
	// Define your methods here
	GetPasswordAndSaltByUsername(username string) (string, string, error)
	GetUserIdentity(username string) (int64, error)
	CreateUser(account, email, nickname, saltedPassword, salt, phone string) error
	UpdateUserInfo(account string, updates map[string]interface{}) error
}

type userRepository struct {
	db *gorm.DB
}

func NewUserRepository(db *gorm.DB) UserRepository {
	return &userRepository{db: db}
}

func (r *userRepository) GetPasswordAndSaltByUsername(username string) (string, string, error) {
	var user struct {
		Password string
		Salt     string
	}
	err := r.db.Table("users").Select("salted_password, salt").Where("account = ?", username).First(&user).Error
	if err != nil {
		return "", "", err
	}
	return user.Password, user.Salt, nil
}

func (r *userRepository) GetUserIdentity(username string) (int64, error) {
	var count int64
	err := r.db.Table("reviewer").Where("account = ?", username).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func (r *userRepository) CreateUser(account, email, nickname, saltedPassword, salt, phone string) error {
	// 创建用户对象
	user := &model.User{
		Account:        account,
		Email:          email,
		Nickname:       nickname,
		Phone:          phone,
		Salt:           salt,
		SaltedPassword: saltedPassword,
	}

	// 保存用户对象
	if err := r.db.Create(user).Error; err != nil {
		return fmt.Errorf("failed to create user: %w", err)
	}

	return nil
}

func (r *userRepository) UpdateUserInfo(account string, updates map[string]interface{}) error {
	if err := r.db.Table("users").Where("account = ?", account).Updates(updates).Error; err != nil {
		return fmt.Errorf("failed to update user info: %w", err)
	}
	return nil
}
